package thread;

import java.util.concurrent.Semaphore;


/**
 * 两个线程交替打印1~100
 *
 */
public class Print100 {


    private final Semaphore S1 = new Semaphore(1);

    private final Semaphore S2 = new Semaphore(0);



    public void print100() {

        final Integer[] i = {0};

        Runnable t1 = () -> {
            try {
                for (int j = 1; j <= 100; j=j+2) {
                    S1.acquire();
                    System.out.println(j + Thread.currentThread().getName());
                    S2.release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        };

        Runnable t2 = () -> {
            try {
                for (int j = 2; j <= 100; j=j+2) {
                    S2.acquire();
                    System.out.println(j + Thread.currentThread().getName());
                    S1.release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        new Thread(t1).start();
        new Thread(t2).start();

    }

    public static void main(String[] args) {
        new Print100().print100();
    }


}
